<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="归属id" prop="sessionId">
        <el-input
          v-model="queryParams.sessionId"
          placeholder="请输入归属会话id"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item label="发送者" prop="label">
        <el-input
          v-model="queryParams.label"
          placeholder="请输入会话发送者"
          clearable
          @keyup.enter="handleQuery"
          style="width: 150px"
        />
      </el-form-item>
      <!-- 将会话标题输入框改为startTime的日期选择框 -->
      <el-form-item label="开始时间" prop="startTime" v-if="!isAdding">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择开始时间"
          style="width: 150px"
        />
      </el-form-item>
      <!-- 将原来的创建时间输入框改为endTime的日期选择框 -->
      <el-form-item label="结束时间" prop="endTime" v-if="!isAdding">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结束时间"
          style="width: 150px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['detail:detail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
        :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="归属会话id" align="center" prop="sessionId" />
      <el-table-column label="会话发送者" align="center" prop="label" />
      <el-table-column label="会话标题" align="center" prop="sessionTitle" />
      <el-table-column label="会话内容" align="center" prop="content" />
      <el-table-column label="创建时间" align="center" prop="timestamp" width="180">
        <template #default="
          scope
        "><span>{{ parseTime(scope.row.timestamp, '{y}-{m}-{d}') }}</span></template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['detail:detail:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['detail:detail:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      v-model:page="queryParams.pageNum"
      v-model:lapageSize="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改detail对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="detailRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="归属会话id" prop="sessionId">
          <el-input v-model="form.sessionId" placeholder="请输入归属会话id" />
        </el-form-item>
        <el-form-item label="会话发送者" prop="label">
          <el-input v-model="form.label" placeholder="请输入会话发送者" />
        </el-form-item>
        <el-form-item label="会话标题" v-if="!isAdding">
          <el-input v-model="form.sessionTitle" placeholder="请输入会话标题" />
        </el-form-item>
        <el-form-item label="会话内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="创建时间" prop="timestamp" v-if="!isAdding">
          <el-date-picker clearable
            v-model="form.timestamp"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Detail">
import {
  selectAllSessionDetail,
  insertSessionDetail,
  updateSessionDetailById,
  dynamicSelectSessionDetail,
  delDetail,
  getDetail,
} from "@/api/detail/detail";
import { onMounted, ref, reactive, toRefs, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();

const detailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isAdding = ref(false);

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        sessionId: null,
        username: null,
        startTime: null,
        endTime: null
    },
    rules: {}
});

const { queryParams, form, rules } = toRefs(data);

// 页面加载时自动执行初始化查询方法
onMounted(() => {
    initData();
});

// 进入页面时执行初始化查询（调用selectAllSessionDetail），确保数据正确绑定到detailList
const initData = () => {
    selectAllSessionDetail().then(response => {
        if (response && response.code === 200 && response.data) {
            const processedData = response.data.map(item => ({
                id: item.id,
                sessionId: item.sessionId,
                label: item.label,
                sessionTitle: item.sessionTitle,
                content: item.content,
        timestamp: new Date(item.timestamp)
            }));
            detailList.value = processedData;
            total.value = processedData.length;
            loading.value = false;
        }
    }).catch(() => {
        loading.value = false;
    });
};

/** 查询detail列表，使用dynamicSelectSessionDetail进行动态查询 */
function getList() {
    loading.value = true;
    const sessionDetailDto = {
        username: queryParams.value.username,
        sessionId: queryParams.value.sessionId,
        startTime: queryParams.value.startTime? new Date(queryParams.value.startTime) : null,
        endTime: queryParams.value.endTime? new Date(queryParams.value.endTime) : null
    };
    dynamicSelectSessionDetail(sessionDetailDto).then(response => {
        console.log("dynamicSelectSessionDetail response:", response);
        if (response && response.code === 200 && response.data && response.data.data) {
            const processedData = response.data.data.map(item => ({
                id: item.id,
                sessionId: item.sessionId,
                label: item.label,
                sessionTitle: item.sessionTitle,
                content: item.content,
                timestamp: new Date(item.timestamp)
            }));
            detailList.value = processedData;
            total.value = processedData.length;
            // 手动触发Vue更新（用于排查问题，若正常可移除）
            proxy.$nextTick(() => {
                proxy.$forceUpdate();
            });
        } else {
            console.error("Failed to get valid data from dynamicSelectSessionDetail:", response);
        }
        loading.value = false;
    }).catch(error => {
        console.error("Error occurred in dynamicSelectSessionDetail:", error);
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
    isAdding.value = false;
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        sessionId: null,
        username: null,
        sessionTitle: null,
        content: null,
        timestamp: null
    };
    proxy.resetForm("detailRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(
    selection
) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length!= 1;
    multiple.value =!selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加detail";
    isAdding.value = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value;
    getDetail(_id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改detail";
        isAdding.value = false;
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["detailRef"].validate(valid => {
        if (valid) {
            if (form.value.id!= null) {
                updateSessionDetailById(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    initData();
                });
            } else {
                const newFormData = {
               ...form.value,
                    sessionTitle: form.value.sessionTitle || null,
                    timestamp: form.value.timestamp || null
                };
                insertSessionDetail(newFormData).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    initData();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除detail编号为"' + _ids + '"的数据项？').then(() => {
        return delDetail(_ids);
    }).then(() => {
        proxy.$modal.msgSuccess("删除成功");
        initData();
    }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('detail/detail/export', {
   ...queryParams.value
    }, `detail_${new Date().getTime()}.xlsx`)
}

// 假设的时间格式化函数，可根据实际需求调整
function parseTime(time, format) {
    console.log("Input time:", time);
    console.log("Format:", format);
    let formattedTime = "";
    if (time) {
        const date = new Date(time);
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        formattedTime = format.replace('y', year).replace('m', month).replace('d', day);
    }
    console.log("Output formatted time:", formattedTime);
    return formattedTime;
}
</script>